package client.ui.view;

import client.UserState;
import client.assets.Icons;
import client.control.Controller;
import client.control.ResponseEntity;
import client.entity.Good;
import client.ui.component.button.MaterialButton;
import client.ui.component.divider.Divider;
import client.ui.component.edittext.InputArea;
import client.ui.component.edittext.TextEdit;
import client.ui.component.layout.VFlowLayout;
import client.ui.theme.ThisFont;
import client.ui.util.MaterialBorder;
import client.ui.util.MaterialColors;
import client.ui.view.base.FrameBase;
import client.ui.view.base.PanelControl;
import client.ui.view.panel.main.GoodsPanel;
import client.ui.view.panel.main.MyDataPanel;
import client.util.ImageUtil;

import com.alibaba.fastjson.JSONObject;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @Description 商品编辑界面
 * @author 孔明浩
 * @Date 2020/4/5
 */
public class EditPage extends FrameBase implements ActionListener{
    private boolean editing = false;
    private Good good;
    private Executor singleThreadExecutor = Executors.newSingleThreadExecutor();
    private final List<TextEdit> textEdits = new ArrayList<>();
    private InputArea inputArea;
    private JPanel addPicPanel;
    private JPanel attributePanel;
    private JPanel descriptionPanel;
    private JPanel showPicPanel;
    private final List<File> images = new ArrayList<>();
    public EditPage(String title){
        super(title);
        this.setIconImage(Icons.edit.getImage());
        initial();
    }

    public EditPage(String title,Good good){
        super(title);
        this.setIconImage(Icons.edit.getImage());
        initial();
        editing = true;
        textEdits.get(0).setText(good.getPrice() + "");
        textEdits.get(1).setText(good.getCategory() == null ? "" : good.getCategory() + "");
        textEdits.get(2).setText(good.getCount() + "");
        textEdits.get(3).setText(good.getGoodName());
        inputArea.setText(good.getDescription());
        this.good = good;
        singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                List<String> urls = JSONObject.parseArray(good.getPic(), String.class);
                File tempPath = new File("./temp");
                tempPath.deleteOnExit();
                if(!tempPath.exists() || !tempPath.isDirectory())
                {
                    if (!tempPath.mkdir()){
                        return;
                    }   //如果不存在，则创建该文件夹,创建失败则返回
                }
                for (String url:urls) {
                    Date now = new Date();
                    File file;
                    FileOutputStream fos = null;
                    //船舰临时图片文件
                    try {
                        BufferedImage bufferedImage = ImageIO.read(new URL(url));
                        file = File.createTempFile("" + now.getTime(),".png",tempPath);
                        fos = new FileOutputStream(file);
                        ImageIO.write(bufferedImage,"png",fos);
                        fos.flush();
                        fos.close();
                        images.add(file);
                        file.deleteOnExit();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        if (fos != null){
                            try {
                                fos.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                }
                updatePanel("showPicPanel");
            }
        });
    }
    protected void initial(){
        initContentPanel();
        this.setSize(new Dimension(680,680));
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    }

    private void initContentPanel(){
        GridBagLayout gridBagLayout = new GridBagLayout();
        GridBagConstraints gridBagConstraints;
        JPanel contentPanel = new JPanel(gridBagLayout);

        initAddPicPanel();
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.weightx = 1;
        gridBagConstraints.weighty = 0.4;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
        contentPanel.add(addPicPanel, gridBagConstraints);

        initAttribute();
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.weighty = 0.6;
        gridBagConstraints.anchor = GridBagConstraints.WEST;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 0.3;
        contentPanel.add(attributePanel, gridBagConstraints);

        initDescription();
        gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.anchor = GridBagConstraints.EAST;
        gridBagConstraints.weightx = 0.7;
        gridBagConstraints.weighty = 0.6;
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        contentPanel.add(descriptionPanel, gridBagConstraints);


        this.setContentPane(contentPanel);

    }

    private void initAddPicPanel(){
        addPicPanel = new JPanel(new BorderLayout());
        //添加图片
        BorderLayout borderLayout = new BorderLayout();
        borderLayout.setVgap(0);
        JPanel addIcon = new JPanel(borderLayout);

        JLabel textLabel = new JLabel("添加图片");
        textLabel.setFont(ThisFont.BIG_BOLD_FONT);
        textLabel.setBorder(new EmptyBorder(12,12,12,12));

        JButton addIconLabel = new JButton(Icons.add);
        addIconLabel.setBorder(null);

        addIcon.add(textLabel, BorderLayout.NORTH);
        addIcon.add(addIconLabel, BorderLayout.CENTER);
        addIconLabel.addActionListener(this);
        addIconLabel.setActionCommand("addIcon");

        //添加的图片展示面板
        showPicPanel = new JPanel();
        JScrollPane scrollPane = new JScrollPane(showPicPanel);
        showPicPanel.add(new JLabel(Icons.head_image));

        addPicPanel.add(scrollPane, BorderLayout.CENTER);
        addPicPanel.add(addIcon, BorderLayout.EAST);
        addPicPanel.add(new Divider(MaterialColors.COSMO_BLUE), BorderLayout.SOUTH);
    }

    //设置商品属性
    private void initAttribute(){
        attributePanel = new JPanel(new VFlowLayout());
        attributePanel.setBorder(MaterialBorder.OCEAN_LINE_BORDER);
        TextEdit nameEdit = new TextEdit("商品名称:");
        TextEdit priceEdit = new TextEdit("设置价格(￥):");
        TextEdit labelEdit = new TextEdit("设置标签(可以留空)");
        TextEdit numEdit = new TextEdit("设置数量(不设置默认为1)");
        //顺序不可改变
        textEdits.add(priceEdit);
        textEdits.add(labelEdit);
        textEdits.add(numEdit);
        textEdits.add(nameEdit);

        attributePanel.add(priceEdit);
        attributePanel.add(labelEdit);
        attributePanel.add(numEdit);
        attributePanel.add(nameEdit);
    }

    //新增描述
    private void initDescription(){
        descriptionPanel = new JPanel(new BorderLayout());
        descriptionPanel.setBackground(MaterialColors.WHITE);
        descriptionPanel.setBorder(MaterialBorder.NORMAL_LINE_BORDER);
        MaterialButton sendButton = MaterialButton.BlueButton("发布",null);
        sendButton.setActionCommand("send");
        sendButton.addActionListener(this);

        JLabel text = new JLabel("写描述");
        text.setForeground(MaterialColors.COSMO_BLUE);
        text.setBorder(new EmptyBorder(4,12,0,12));
        text.setFont(ThisFont.MIDDLE_FONT);
        inputArea = new InputArea(null,sendButton,null);
        inputArea.setInputAreaFont(ThisFont.BIG_FONT);
        descriptionPanel.add(text, BorderLayout.NORTH);
        descriptionPanel.add(inputArea, BorderLayout.CENTER);
    }

    /**
     * @Description 更新面板
     * @param panelName 支持showPicPanel
     * @author 孔明浩
     * @Date 2020/4/6
     */
    @Override
    public void updatePanel(String panelName) {
        if ("showPicPanel".equals(panelName)){
            showPicPanel.removeAll();
            for (File file : images){
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        ImageIcon imageIcon = new ImageIcon(file.getPath());
                        JLabel label = new JLabel(ImageUtil.getImageIcon(imageIcon,null,0,250));
                        JPopupMenu popupMenu = new JPopupMenu();
                        JMenuItem delete = new JMenuItem("删除");
                        popupMenu.add(delete);
                        label.setComponentPopupMenu(popupMenu);
                        delete.addActionListener(new ActionListener() {
                            @Override
                            public void actionPerformed(ActionEvent e) {
                                images.remove(file);
                                updatePanel("showPicPanel");
                            }
                        });

                        showPicPanel.add(label);
                    }
                });
            }
            addPicPanel.remove(0);
            JScrollPane scrollPane = new JScrollPane(showPicPanel);
            addPicPanel.add(scrollPane, 0);
            addPicPanel.validate();
        }
    }

    /**
     * @Description
     * @param e 通过e的setActionCommand获取下面的操作
     * @author 孔明浩
     * @Date 2020/4/5
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        if ("addIcon".equals(e.getActionCommand())){
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileFilter(new FileNameExtensionFilter(
                    "图片文件(*.jpg,*.jpeg,*.png, *.gif)","jpg","jpeg", "png", "gif"));
            fileChooser.showOpenDialog(EditPage.this);
            if (fileChooser.getSelectedFile() != null){
                File file = fileChooser.getSelectedFile();
                EditPage.this.images.add(file);
                updatePanel("showPicPanel");
            }
        } else if ("send".equals(e.getActionCommand())){
            //判断数据是否合法
            double price;
            int label = 1;
            int num = 1;
            String name;
            try{
                price = Double.parseDouble(textEdits.get(0).getText());
                if (price <= 0){
                    throw new Exception();
                }
            } catch (Exception e1){
                textEdits.get(0).setErrorText("请输入合理的价格");
                return;
            }
            try{
                if (textEdits.get(1).getText() != null && textEdits.get(1).getText().length() > 0){
                    label = Integer.parseInt(textEdits.get(1).getText());
                }
            } catch (Exception e1){
                textEdits.get(1).setErrorText("只能是整数");
                return;
            }
            try{
                if (textEdits.get(2).getText().length() > 0){
                    num = Integer.parseInt(textEdits.get(2).getText());
                }
                if (num <= 0){
                    throw new Exception();
                }
            } catch (Exception e1){
                textEdits.get(2).setErrorText("请输入商品数量(整数)");
                return;
            }
            name = textEdits.get(3).getText();
            if (name == null || name.length() == 0){
                textEdits.get(3).setErrorText("商品名不能为空");
            }
            //判断没有异常之后
            for (TextEdit t: textEdits){
                t.setErrorText("");
            }

            int code = JOptionPane.showConfirmDialog(this,
                    "请确认信息无误","确认",JOptionPane.YES_NO_OPTION);
            if (code == JOptionPane.YES_OPTION){
                Integer finalLabel = label;
                int finalNum = num;
                singleThreadExecutor.execute(new Runnable() {
                    @Override
                    public void run() {
                        ResponseEntity responseEntity;
                        //判断是否是在编辑或者新建
                        if (editing){
                            responseEntity = Controller.GOOD_CONTROL.setGoodInfo(
                                    UserState.getToken(),good.getGoodId(),name,price,
                                    finalLabel, finalNum,inputArea.getText(),images
                            );
                        } else {
                            showMessage("正在发布请耐心等待...");
                            responseEntity = Controller.GOOD_CONTROL.addGood(
                                    UserState.getToken(),name,price,
                                    finalLabel, finalNum,inputArea.getText(),images
                            );
                        }
                        if (responseEntity.getCode() == 0){
                            PanelControl p = PanelControl.panels.get("MyDataPanel");
                            if (p instanceof MyDataPanel){
                                ((MyDataPanel) p).getMyGoodList();
                            }
                            p = PanelControl.panels.get("GoodsPanel");
                            if (p instanceof GoodsPanel){
                                p.updatePanel("itemPanel");
                            }
                            showMessage("创建成功");
                        } else {
                            showMessage("请求失败," + responseEntity.getMessage());
                        }

                    }
                });
            }
        }
    }

    /**
     * @Description 显示信息阻断，用来做网络请求或者其他操作的回显
     * @param message 显示信息
     * @author 孔明浩
     * @Date 2020/4/5
     */
    private void showMessage(String message){

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JOptionPane.showMessageDialog(EditPage.this,message);
                if ("创建成功".equals(message)){
                    dispose();
                }
            }
        });
    }
}
